<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/10/31
 * Time: 17:53
 */
namespace C\lib{

    use C\mod\express;

    require LIB_PATH. 'Wxpaapi/lib/WxPay.Config.php';
    class Wxapi{
        public static function getOpenid($code){
            $url='https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx08a944d5a385e626&secret=a7c5fb282f444d28647f69657fcb8fe0&code='.$code.'&grant_type=authorization_code';
            $data=self::get($url);
            return $data;
        }
        public static function getSignPackage() {
           // echo 123;
            $jsapiTicket = self::getJsApiTicket();
            //var_dump($jsapiTicket);exit;

            // 注意 URL 一定要动态获取，不能 hardcode.
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
            $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

            $timestamp = time();
            $nonceStr = self::createNonceStr();

            // 这里参数的顺序要按照 key 值 ASCII 码升序排序
            $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

            $signature = sha1($string);

            $signPackage = array(
                "appId"     => \WxPayConfig::APPID,
                "nonceStr"  => $nonceStr,
                "timestamp" => $timestamp,
                "url"       => $url,
                "signature" => $signature,
                "rawString" => $string
            );
            return $signPackage;
        }

        private static function createNonceStr($length = 16) {
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            $str = "";
            for ($i = 0; $i < $length; $i++) {
                $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
            }
            return $str;
        }

        private static function getJsApiTicket() {
            // jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
            $data = json_decode(self::get_php_file(LIB_PATH."radis/jsapi_ticket.php"));
            if ($data->expire_time < time()) {
                $accessToken = self::getAccessToken();

                // 如果是企业号用以下 URL 获取 ticket
                // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
                $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
                $res = json_decode(self::httpGet($url));
                $ticket = $res->ticket;
                if ($ticket) {
                    $data->expire_time = time() + 7000;
                    $data->jsapi_ticket = $ticket;
                    self::set_php_file(LIB_PATH."radis/jsapi_ticket.php", json_encode($data));
                }
            } else {
                $ticket = $data->jsapi_ticket;
            }

            return $ticket;
        }
        public static function get($url) {
            $ch = curl_init();
            curl_setopt($ch,CURLOPT_URL,$url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            $output=curl_exec($ch);
            //var_dump($output);exit;
            curl_close($ch);
            return $output; //exit;
        }
        public static function getAccessToken() {

            // access_token 应该全局存储与更新，以下代码以写入到文件中做示例
            $data = json_decode(self::get_php_file(LIB_PATH."radis/access_token.php"));
            if ($data->expire_time < time()) {
                $appid=\WxPayConfig::APPID;
                $sercret=\WxPayConfig::APPSECRET;
                //bd20170601wxgzh
                //https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx08a944d5a385e626&secret=a7c5fb282f444d28647f69657fcb8fe0";
               // echo $url; exit;
                $res = json_decode(self::get($url));

                //var_dump($res); exit;
                $access_token = $res->access_token;
                if ($access_token) {
                    $data->expire_time = time() + 7000;
                    $data->access_token = $access_token;
                    self::set_php_file(LIB_PATH."radis/access_token.php", json_encode($data));
                }
            } else {

                $access_token = $data->access_token;
            }
           // var_dump($access_token);exit;
            return $access_token;
        }

        public static function httpGet($url) {
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_TIMEOUT, 500);
            // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
            // 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($curl, CURLOPT_URL, $url);
            $res = curl_exec($curl);
            curl_close($curl);
            return $res;
        }
        private static function httpPost($url,$data){
            $curl = curl_init();
            //设置抓取的url
            curl_setopt($curl, CURLOPT_URL,$url);
             //设置头文件的信息作为数据流输出
            curl_setopt($curl, CURLOPT_HEADER, 1);
              //设置获取的信息以文件流的形式返回，而不是直接输出。
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
              //设置post方式提交
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
             //执行命令
            $data = curl_exec($curl);
           // var_dump($data);exit;
             //关闭URL请求
            curl_close($curl);
             //显示获得的数据
             return $data;
        }

        private static function get_php_file($filename) {
            return trim(substr(file_get_contents($filename), 15));
        }
        private static function set_php_file($filename, $content) {
            $fp = fopen($filename, "w");
            fwrite($fp, "<?php exit();?>" . $content);
            fclose($fp);
        }
        /*
         * 设置所属行业
         */
        public static function industry(){
            $access_token=self::getAccessToken();
            $data['access_token']=$access_token;
            $data['industry_id1']=2;
            $data['industry_id2']=13;
            $a=json_encode($data);
            $url="https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token=".$access_token;
            $data=self::httpPost($url,$a);
            return $data;
        }
        /*
         * 获取设置的行业信息
         */
        public static function getInfo(){
            $access_token=self::getAccessToken();
            //$url="https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=".$access_token;
            $url="https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token=".$access_token;
            $data=self::get($url);
            $b=json_decode($data,true);
            var_dump($b);
        }
        /*
         * 获取模板号
         */
        public static function gettemid(){
            $access_token=self::getAccessToken();
            $data['access_token']=$access_token;
            $data['template_id_short']='OPENTM201027336';
            $url="https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=".$access_token;
           // $url="https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token=".$access_token;
            $data=self::httpPost($url,$data);
            $b=json_decode($data,true);
            var_dump($b);
        }
        /*
         *获取模板列表
         */
        public static function temlist(){
            $access_token=self::getAccessToken();

            $url="https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=".$access_token;
            // $url="https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token=".$access_token;
            $data=self::get($url);
            $b=json_decode($data,true);
            var_dump($b);
        }
        /*
         * 发送模板消息
         * type 0取快递 1寄快递 2物流托运  每个支付页面都不一样 判断用哪个支付页面
         * mtype :1接单后通知用户 2处理订单后通知用户 3用户付款成功通知
         */
        public static function sendInfo($openid,$type,$order_id,$mtype,$worker_name,$phone,$id,$money,$time_add){
            $access_token=self::getAccessToken();
            //echo $access_token;exit;
            //echo $mtype;//exit;
            $v=[];
            if($mtype==2){
                //echo '222';exit;
                if($type==0){
                    //echo 66;exit;
                    $one_type='代取员';
                    $url='http://s.biandikeji.com/work/bpost/wxqpay?id='.$id;
                }
                if($type==1){
                    $one_type='快递员';
                    $url='http://s.biandikeji.com/work/bpost/wxhpay?id='.$id;
                }
                if($type==2){
                    $one_type='托运员';
                    $url='http://s.biandikeji.com/work/bpost/wxtpay?id='.$id;
                }
                $v =[
                    'touser'=>$openid,
                    //'template_id'=>'7emhWa94awWuufiP4z1ZPCEAyHeONx8wt0QzpexTGX0',
                    'template_id'=>'9MNJTVtmNGpvgjkhdc1XO3JrOWXz2v_HWbMa9Qy4MzM',
                    'url'=>$url,
                    'miniprogram' => [
                        'appid'=>'',
                        'pagepath'=>''
                    ],
                    'data'=>[
                        'first'=>[
                            'value'=>'你好，你还有宝贝末付款。'
                        ],
                        'keyword1'=>[
                            'value'=>'未付款'
                        ],
                        'keyword2'=>[
                            'value'=>$money.'元'
                        ],
                        'keyword3'=>[
                            'value'=>date("Y-m-d H:i:s",$time_add)
                        ],
                        'remark'=>[
                            'value'=>$one_type.$worker_name
                        ]
                    ]
                ];
            }elseif ($mtype==1){
                //echo 111;exit;
                $v =[
                    'touser'=>$openid,
                    'template_id'=>'7emhWa94awWuufiP4z1ZPCEAyHeONx8wt0QzpexTGX0',

                    'url'=>'',
                    'miniprogram' => [
                        'appid'=>'',
                        'pagepath'=>''
                    ],
                    'data'=>[
                        'channel'=>[
                            'value'=>'微信公众号'
                        ],
                        'orderNumber'=>[
                            'value'=>$order_id
                        ],
                        'state'=>[
                            'value'=>'进入收单状态'
                        ],
                        'doSomething'=>[
                            'value'=>$worker_name.'联系方式:'.$phone
                        ],
                        'remark'=>[
                            'value'=>'谢谢您的支持'
                        ]
                    ]
                ];
            }else{
                $v =[
                    'touser'=>$openid,
                    'template_id'=>'8yNm6mL_q7vd3SPN0YFJXPfzVvZsG4uduHkNxXyIIOU',

                    'url'=>'',
                    'miniprogram' => [
                        'appid'=>'',
                        'pagepath'=>''
                    ],
                    'data'=>[
                        'first'=>[
                            'value'=>'您已付款成功。'
                        ],
                        'keyword1'=>[
                            'value'=>$order_id
                        ],
                        'keyword2'=>[
                            'value'=>$worker_name
                        ],
                        'keyword3'=>[
                            'value'=>$phone
                        ],
                        'remark'=>[
                            'value'=>'感谢您的支持！祝您生活愉快'
                        ]
                    ]
                ];
            }

            $c=json_encode($v);
            //var_dump($c);exit();

            $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
            $a=self::httpPost($url,$c);

            preg_match_all('/(.*)"errmsg":"(.*)",(.*)/',$a,$b);
            $errmsg = $a&&isset($b[2]) ? $b[2] : '';
            //var_dump($data);
            return $errmsg[0];
        }
    }
}
